package org.languageguide.user;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.languageguide.storage.DBConnector;

public class UserManager {	

	public static User getUser(HttpSession session){
		Object obj = session.getAttribute(User.sessionId);
		if (obj != null)
			return (User)obj;
		else return null;
	}

	public void removeUser(HttpSession session){
		session.removeAttribute(User.sessionId);
	}
	
	public void rememberUser(HttpSession session, HttpServletResponse response){
		User user = (User) session.getAttribute(User.sessionId);
		Cookie cookie = new Cookie("user", user.getEmail() + "&" + user.getHashedPw());
		response.addCookie(cookie);
	}

	public static User loginFromCookie(HttpServletRequest request){
		String value = getUserCookieValue(request);
		System.out.println("value:" + value);
		if (value != null){
			int loc = value.indexOf("&");
			String[] rslts = loc != -1 ? value.split("&") : null;
			User user = getUser(rslts[0]);
			if (user != null){
				if (user.getHashedPw().equals(rslts[1])){
					request.getSession().setAttribute(User.sessionId, user);
					return user;
				}
				//delete invalid cookie; 
			}			
		}
		return null;
		//Cookie tokenCookie = createTokenCookie(user);
		//log.debug("Created token cookie : " + tokenCookie);
	}	
	
	public static User getUser(String email){
		String hsUserSql = "SELECT * FROM Users2 WHERE Users2.email = ?";
		DBConnector connector = DBConnector.getInstance();
		Connection connection = connector.getConnection();
		try {
			PreparedStatement queryUser = connection.prepareStatement(hsUserSql);
			queryUser.setString(1, email);
			ResultSet rs = queryUser.executeQuery();
			while (rs.next()){
				User user = new User(rs);
				return user;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			connector.close(connection);
		}
		System.out.println("coun't find user");
		return null;
	}

	public User getUser(String email, String pw){
		String hsUserSql = "SELECT * FROM Users2 WHERE Users2.email = ? AND (HashPassword = ? OR Password = ?)";
		DBConnector connector = DBConnector.getInstance();
		Connection connection = connector.getConnection();
		String hashed = PasswordUtility.getHash(pw);
		try {
			PreparedStatement queryUser = connection.prepareStatement(hsUserSql);
			queryUser.setString(1, email);
			queryUser.setString(2, hashed);
			queryUser.setString(3, pw);
			ResultSet rs = queryUser.executeQuery();
			while (rs.next()){
				User user = new User(rs);
				return user;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			connector.close(connection);
		}
		System.out.println("coun't find user");
		return null;
	}

	public static String getUserCookieValue(HttpServletRequest request){
		Cookie[] cookies = request.getCookies();
		if(cookies == null || cookies.length < 1) {
			return null;
		}

		for (javax.servlet.http.Cookie cookie : cookies) {
			//System.out.println("name:" + cookie.getName() + ":");
			if (cookie.getName().equals("user")) {
				return cookie.getValue();
			}
		}
		return null;
	}


	public User registerUser(String name, String email, String password, String lang){
		User user = new User(name, email, password, lang);
		user.store();
		return user;
	}


	String hsUserSql = "SELECT * FROM Users2 WHERE Users2.email = ?";
	public boolean hasUser(String email){
		DBConnector connector = DBConnector.getInstance();
		Connection connection = connector.getConnection();
		try {
			PreparedStatement queryUser = connection.prepareStatement(hsUserSql);
			queryUser.setString(1, email); 
			ResultSet rs = queryUser.executeQuery();
			while (rs.next()){
				return true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			connector.close(connection);
		}
		System.out.println("coun't find user");
		return false;
	}
	
	
	public boolean confirmEmail(String code){
		String verifyUserSql = "Update Users2 SET Confirmed = 1 WHERE Code = ?";
		DBConnector connector = DBConnector.getInstance();
		Connection connection = connector.getConnection();
		try {
			PreparedStatement confirmUserEmail = connection.prepareStatement(verifyUserSql);
			confirmUserEmail.setString(1, code);			
			
			
			confirmUserEmail.execute();
			int count = confirmUserEmail.getUpdateCount();
			if (count > 0){
				return true;
			}
			else{
				return false;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			connector.close(connection);
		}
		System.out.println("coun't find user");
		return false;
	}
	
	
	
	String sql = "SELECT * FROM Users2 LEFT JOIN Language ON Users2.editing_language = Language.code WHERE Users2.password = ? AND Users2.email = ?";
	public boolean loadUser(HttpSession session, String email, String password){
		DBConnector connector = DBConnector.getInstance();
		Connection connection = connector.getConnection();
		try {
			PreparedStatement queryUser = connection.prepareStatement(sql);
			queryUser.setString(1, password);
			queryUser.setString(2, email); 
			ResultSet rs = queryUser.executeQuery();
			while (rs.next()){
				User bean = new User(rs);
				System.out.println("found user");
				session.setAttribute(User.sessionId, bean);
				return true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{	
			connector.close(connection);
		}
		return false;
	}
	
}
